using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Snowy.Data;
using Snowy.Dtos;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;


namespace Snowy.Services
{
  

    public class UserService  
    {
     

        private readonly AppSettings _appSettings;
        private readonly ApplicationDbContext _dbContext;

        public UserService(IOptions<AppSettings> appSettings, ApplicationDbContext dbContext)
        {
            _appSettings = appSettings.Value;
            _dbContext = dbContext;
        }

        internal TokenEntity generateJwtToken(SysUser   user)
        {
          
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.JwtKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] 
                    { new Claim("UserId",user.Id.ToString())
                    ,new Claim("Account",user.Account)
                    ,  new Claim("Name", user.Name)
                    ,new Claim("SuperAdmin",user.AdminType.ToString())
                     }
                ),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return  new TokenEntity()
            {
                access_token = tokenHandler.WriteToken(token),
                expires_in = (int)tokenDescriptor.Expires.GetValueOrDefault().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds
            };
        }

        internal SysUser GetUser(Claim[] claims)
        {
            SysUser user = null;
            if (long.TryParse(claims.FirstOrDefault(c => c.Type == "UserId").Value, out long userid))
            {
                var Account = claims.FirstOrDefault(c => c.Type == "Account").Value;
                var query = from u in _dbContext.SysUsers where u.Id == userid && u.Account == Account select u;
                user = query.FirstOrDefault();
            }
            return user;
        }
    }
}
